//
//  QRCodeViewController.swift
//  JKTools
//
//  Created by 姜奎 on 2024/4/19.
//

import Cocoa
import CoreImage

class QRCodeViewController: NSViewController {
    
    @IBOutlet var textView: NSTextView!
    
    @IBOutlet weak var qrCodeImageView: NSImageView!
    
    @IBOutlet weak var qrCodeImageCell: NSImageCell!
    
    @IBOutlet weak var toQRCodeBtn: NSButton!
    
    @IBOutlet weak var toStringBtn: NSButton!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do view setup here.
    
        qrCodeImageView.registerForDraggedTypes([.png, .URL, .fileURL])
        qrCodeImageView.addTrackingArea()
        qrCodeImageView.setMouseDown(.right) {[weak self] event in
            self?.showMenu(event)
        }
    }
    
    override func viewWillAppear() {
        super.viewWillAppear()
    }
    
    @IBAction func toString(_ sender: Any) {
        
        guard let image = qrCodeImageView.image else {
            return
        }
        
        guard let string = QRCode.toString(image) else { return }
        
        textView.string = string
        
    }
    
    @IBAction func toQRCode(_ sender: Any) {
        let input = textView.string
        guard input.isEmpty == false else {
            return
        }
        
        guard let image = QRCode.toQRCode(input,size: qrCodeImageView.bounds.size) else { return }
        qrCodeImageView.image = image
    }
    
    func showMenu(_ event: NSEvent) {
        guard let image = qrCodeImageView.image else { return }
        let menu = NSMenu.menu().addItem(title: "保存图片") {
            NSSavePanel.save(message: "保存二维码", name: "二维码.png") { toSavePath in
                guard let imageData = image.tiffRepresentation,let toSavePath = toSavePath else { return }
                _ = try? imageData.write(to: toSavePath)
            }
        }
        NSMenu.popUpContextMenu(menu, with: event, for: qrCodeImageView)
    }
}

